package com.coman404.base;

import com.coman404.base.handler.UDPClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * @author NotFound404 at 2024/5/31
 * code code always code
 */
public class UDPClient {
    public static void main(String[] args){

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioDatagramChannel.class)
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        protected void initChannel(NioDatagramChannel ch) throws Exception {
                            ch.pipeline().addLast(new UDPClientHandler());
                        }
                    });
            ChannelFuture f = bootstrap.connect("192.168.0.111",8089).sync();
            if (f.isSuccess()){
                System.out.println("连接成功");
            }
            Channel channel = f.channel();
            channel.writeAndFlush(new DatagramPacket(channel.alloc().buffer().writeBytes("hello world".getBytes(StandardCharsets.UTF_8)),new InetSocketAddress("192.168.0.111",8089)));
            channel.closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }

    }
}
